<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/4/23
 * Time: 15:19
 */

namespace app\logic\index\timbre;


use app\logic\BaseLogic;

class TimbreLogic extends BaseLogic
{
    protected $model;

    protected static $instance;

    public function __construct()
    {
        parent::__construct();
        $this->model = \app\model\moyin\TimbreModel::getInstance();
    }

    public static function getInstance()
    {
//        if(is_object(self::$instance)){
//            return self::$instance;
//        }

        return  new self();
    }

    public function getList($param)
    {
        $where = [
            'isdel'=>0,
            'status'=>1,
        ];
        if(!empty($param['lang'])){
            $where['lang'] = $param['lang'];
        }else{
            $where['lang'] = '普通话';
        }
        $fields = ['id','trait','name','timbreid','scenes','icon','example_url','speak_speed'];

        $list =  $this->model->getWhere($where)->orderBy('sort', 'desc')->get($fields);
        $data = [];
        foreach($list as $item){
            $data[$item['trait']] = [
                'name'=>$item['trait']
            ];
        }

        foreach($list as $item){
            if(!isset($data[$item['trait']])){
                continue;
            }
            $data[$item['trait']]['list'][] = $item;
        }
        $data = array_values($data);

        //默认选择放在首位
        $firsts = [];
        if(!empty($param['selected_id'])){
            foreach($data as $k=>$val){
                foreach ($val['list'] as $v){
                    if($v['id']==$param['selected_id']){
                        $firsts = $data[$k];
                        $first = [];
                        foreach ($firsts['list'] as $kk=>$f){
                            if($f['id']==$param['selected_id']){
                                $first = $f;
                                unset($firsts['list'][$kk]);

                                break;
                            }
                        }
                        $firsts['list'] = array_values($firsts['list']);
                        array_unshift($firsts['list'],$first);
                        unset($data[$k]);

                        break;
                    }
                }
            }
        }
        $data = array_values($data);

        $firsts && array_unshift($data,$firsts);
        return $data;
    }
}